package com_.dxy_test_.async_;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description 测试FutureTask多线程等待结果返回
 * @Author dangxianyue
 * @Date 2022/11/3 9:52
 */
public class FutureTaskTest {

    private static ExecutorService threadPool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(100), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        FutureTaskTest test = new FutureTaskTest();
        String s1 = null, s2 = null;
        long start = System.currentTimeMillis();

        FutureTask<String> task1 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return test.f1();
            }
        });

        FutureTask<String> task2 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return test.f2();
            }
        });

        threadPool.submit(task1);
        threadPool.submit(task2);

        try {
            s1 = task1.get();
            s2 = task2.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        threadPool.shutdown();

        System.out.println(s1 + ", " + s2);
        System.out.println("耗时：" + (System.currentTimeMillis() - start));
        //耗时：2030
    }

    private String f1() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "你好";
    }

    private String f2() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "张三";
    }
}
